package service;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import bean.StudentBean;

@Component("studentService")
public class StudentService {

	@Autowired
	private SessionFactory sessionFactory;
	
	public void save(){
		
		Session session=null;
		Transaction tran=null;
		
		try {
			session=sessionFactory.getCurrentSession();
			tran=session.beginTransaction();
			StudentBean stu=new StudentBean();
			stu.setStuId(3);
			stu.setClassId("3");
			stu.setStuName("admin3");
			session.save(stu);
			
			tran.commit();
		} catch (Exception e) {
			e.printStackTrace();
			tran.rollback();
		}finally{
			//getCurrentSession无须手动关闭
		}
		
	}
	
	/**
	 * 测试在spring管理事务。（Hibernate不再参与事务的提交与回滚）
	 * 本类的save方法的事务是由Hibernate管理的，所以要在hibernate配置文件的设置
	 * <property name="current_session_context_class">thread</property>
	 * @param args
	 */
	public static void main(String[] args) {
		ApplicationContext context=new ClassPathXmlApplicationContext("spring.xml");
		StudentService stuService=(StudentService)context.getBean("studentService");
		stuService.save();
	
	}
	
}
